package com.tyrone.algorithm.linear;


import java.util.Iterator;

public class Stack<T> implements Iterable<T>{
    //记录首结点
    private Node head;
    //栈中的元素的个数
    private int N;

    public Stack() {
        this.head = new Node(null,null);
        N = 0;
    }

    /**
     * 判断栈是否为空，是返回true，否返回false
     * @return
     */
    public boolean isEmpty(){
        return N==0;
    }

    /**
     * 获取栈中元素的个数
     * @return
     */
    public int size(){
        return N;
    }

    /**
     * 弹出栈顶元素
     * @return
     */
    public T pop(){
        Node pop=head.next;
        if (pop==null){
            return null;
        }
        pop.next = pop.next.next;
        N--;
        return pop.item;
    }

    /**
     * 向栈中压入元素t
     * @param t
     */
    public void push(T t){
        Node pop = head.next;
        Node node = new Node(t,pop);
        head.next=node;
        N++;
    }

    @Override
    public Iterator<T> iterator() {
        return new SIterator();
    }


    private class SIterator implements Iterator<T>{
        private Node n = head;
        @Override
        public boolean hasNext() {

            return n.next!=null;
        }

        @Override
        public T next() {
            Node node = n.next;
            n=n.next;
            return node.item;
        }
    }

    private class Node{
        private T item;
        private Node next;

        public Node(T item,Node next){
            this.item = item;
            this.next = next;
        }
    }
}
